﻿using KAsFrame.Application.Contracts.Certificate;
using KAsFrame.Common.Application;
using KAsFrame.Common.Dto;
using KAsFrame.Common.Extensions;
using KAsFrame.Domain.Certificate.Dto;
using KAsFrame.Domain.Certificate.Entities;
using KAsFrame.Domain.User.Entities;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace KAsFrame.Application.AppService.Certificate
{
    public class CertificateAppService : CommonCurdAppService<long, CertificateInfo, CertificateCreateDto, CertificateCreateDto, CertificateDto>, ICertificateAppService
    {
        public CertificateAppService(ISqlSugarClient db) : base(db)
        {
        }

        public override Task<long> CreateAsync(CertificateCreateDto createDto)
        {
            if (!_db.Queryable<Template>().Any(x => x.Id == createDto.Tid))
                throw new Exception("所选模板不存在");
            if (!_db.Queryable<UserInfo>().Any(x => x.Id == createDto.Uid))
                throw new Exception("所选用户不存在");
            foreach (var item in createDto.LabelInfoDic.Keys)
                if (createDto.LabelInfoDic[item].Length > 12)
                    throw new Exception("内容不能大于12个字符");

            return base.CreateAsync(createDto);
        }

        public override async Task<PageReturnDto<CertificateDto>> GetPageListAsync(PageReqDto pageReqDto)
        {
            Expressionable<CertificateInfo> exp = Expressionable.Create<CertificateInfo>();
            if (pageReqDto.Condition.Count > 0)
            {
                var condition = pageReqDto.Condition;

                //var nameKey = condition.Keys.FirstOrDefault(x => x.Contains("name", StringComparison.OrdinalIgnoreCase));
                //if (nameKey != null)
                //    exp = exp.And(x => x.Name.Contains(condition[nameKey].ToString()));
            }

            return await PageAsync(pageReqDto.PageIndex, pageReqDto.PageSize, exp, pageReqDto.OrderBy);
        }

        public async Task<CertificateInfoDto> GetInfoAsync(long id)
        {
            var resultDto = (await _db
                 .Queryable<CertificateInfo, Template>((c, t) => c.Tid == t.Id)
                 .Where((c, t) => c.Id == id)
                 .Select((c, t) => new CertificateInfoDto()
                 {
                     TempName = t.TempName,
                     Title = t.Title,
                     ImgBase64 = t.ImgBase64,
                     BackgroundColor = t.BackgroundColor,
                     CertificateNo = c.Id.ToString(),
                     LabelInfos = c.LabelInfos
                 })
                 .ToListAsync()).FirstOrDefault();
            if (resultDto == null)
                throw new Exception("数据不存在");
            return resultDto;
        }
    }
}
